package com.millstein.realtime.util;

import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Description
 * @Author tsing
 * @Date 2024-10-17 16:26
 */
public class IkUtil {
    /**
     * 关键词分词
     * @param keyword 关键词
     * @return
     */
    private static List<String> split(String keyword) {
        // 1.创建ik分词结果对象
        StringReader reader = new StringReader(keyword);
        IKSegmenter ikSegmenter = new IKSegmenter(reader, true);

        // 2.将分词结果对象的值放到返回的list中
        List<String> returnList = new ArrayList<>();
        try {
            Lexeme le = ikSegmenter.next();
            while (le != null) {
                returnList.add(le.getLexemeText());
                le = ikSegmenter.next();
            }
        } catch (IOException ignore) {}

        // 3.返回结果
        return returnList;
    }

    /**
     * 关键词分词
     * @param keyword 关键词
     * @param repeatable 是否允许结果重复
     * @return
     */
    public static List<String> split(String keyword, boolean repeatable) {
        if (repeatable) {
            return split(keyword);
        } else {
            List<String> split = split(keyword);
            return new ArrayList<>(new HashSet<>(split));
        }
    }
}
